package net.lzzy.service;

import net.lzzy.entity.Article;
import net.lzzy.repository.ArticleRepository;
import net.lzzy.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

//服务层Article
@Service
public class ArticleService {

    @Autowired
    private ArticleRepository articleRepository;
    private CommentRepository commentRepository;

    //分页展示
    public Page<Article> pageArticle(int page, int size){
        Pageable pageable = PageRequest.of(page,size);
        return articleRepository.findAll(pageable);
    }
    public Article findArticleById(Integer id){
        if(articleRepository.findById(id).isPresent()){
            return articleRepository.findById(id).get();
        }
        else{
            return null;
        }
    }

//    查询所有文章，用于后台文章管理
    public List<Article> findAll(){
        return articleRepository.findAll();
    }

    //根据ID删除文章,由于只设置了单向多对一，并设置了级联，直接调用删除评论的接口即可（级
//    联只在设置的一侧有效，当使用文章删除方法时，由于外键约束导致失败）
    public void deleteById(Integer id){
        Article article=findArticleById(id);
        commentRepository.deleteByArticle(article);
    }

//    修改文章
    public void updateArticleById(Integer id,String title,String category,String content){
        Article article=findArticleById(id);
        article.setTitle(title);
        article.setCategory(category);
        article.setContent(content);
        articleRepository.save(article);
    }

//    新增文章
    public  Article addArticle(String title,String category,String content){
        Article article=new Article();
        article.setTitle(title);
        article.setCategory(category);
        article.setContent(content);
        article.setDate(new Date());
        return articleRepository.save(article);
    }
}
